package org.zachary.creditbusiness.commodityandhouse.controller;

import org.zachary.creditbusiness.commodityandhouse.entity.HouseDetails;

import org.zachary.creditbusiness.commodityandhouse.service.HouseDetailsService;

import org.zachary.creditbusiness.commodityandhouse.dto.HouseDetailsWithHouseDTO;
import org.zachary.creditbusiness.commodityandhouse.entity.House;
import org.zachary.creditbusiness.commodityandhouse.service.HouseDetailsService;
import org.zachary.creditbusiness.commodityandhouse.service.HouseService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import org.springframework.http.ResponseEntity;


import org.zachary.creditbusiness.commodityandhouse.dto.HouseDetailsWithHouseDTO;
import org.zachary.creditbusiness.commodityandhouse.entity.House;
import org.zachary.creditbusiness.commodityandhouse.service.HouseService;


import java.util.Optional;
@RestController
@RequestMapping("/house-details")
public class HouseDetailsController {

    @Autowired
    private HouseDetailsService houseDetailsService;

    @Autowired
    private HouseService houseService;


    @GetMapping("/{id}")
    public ResponseEntity<HouseDetailsWithHouseDTO> getHouseDetailsById(@PathVariable Integer id) {
        Optional<HouseDetails> houseDetailsOptional = Optional.ofNullable(houseDetailsService.getHouseDetailsById(id));
        if (houseDetailsOptional.isPresent()) {
            HouseDetails houseDetails = houseDetailsOptional.get();
            Integer houseId = houseDetails.getHouseId();

            House house = houseService.getHouseById(houseId);

            HouseDetailsWithHouseDTO dto = new HouseDetailsWithHouseDTO(houseDetails, house);
            return ResponseEntity.ok(dto);
        } else {
            return ResponseEntity.notFound().build();
        }
    }






    @PostMapping
    public HouseDetails createHouseDetails(@RequestBody HouseDetails houseDetails) {
        return houseDetailsService.createHouseDetails(houseDetails);
    }

    @PutMapping("/{id}")
    public HouseDetails updateHouseDetails(@PathVariable Integer id, @RequestBody HouseDetails houseDetails) {
        houseDetails.setId(id);
        return houseDetailsService.updateHouseDetails(houseDetails);
    }

    @DeleteMapping("/{id}")
    public void deleteHouseDetails(@PathVariable Integer id) {
        houseDetailsService.deleteHouseDetails(id);
    }


    @GetMapping
    public List<HouseDetails> getAllHouseDetails() {
        return houseDetailsService.getAllHouseDetails();
    }
}
